package cn.xawl.interview.thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

/**
 * @author lh
 * @date 2020/08/27 15:19:54
 * 获取线程的方式：
 * 1. 继承Thread类
 * 2. 实现Runnable接口
 * Java中第三种获得线程的方式：实现Callable接口
 * 
 **/
public class CallableDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        FutureTask<Integer> futureTask = new FutureTask<>(new MyThread());

        new Thread(futureTask, "AA").start();



        /*while (!futureTask.isDone()) {
        }*/

        Integer res = futureTask.get();//要求获得Callable线程的计算结果，如果没有计算完成会阻塞。
        System.out.println("result = " + (100 + res));

        System.out.println("aaa");


    }
}

/**
 * <p>Callable接口具有返回值
 */
class MyThread implements Callable<Integer> {

    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName() + "\t进入call,执行计算操作");

        TimeUnit.SECONDS.sleep(2);

        return 1024;
    }


}
